package com.neu.flashmall.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.flashmall.user.entity.UmsAddress;
import com.neu.flashmall.user.mapper.UmsAddressMapper;
import com.neu.flashmall.user.service.UmsAddressService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UmsAddressServiceImpl implements UmsAddressService {
    @Resource
    private UmsAddressMapper umsAddressMapper;

    @Override
    public PageInfo<UmsAddress> getPaged(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<UmsAddress> umsAddresses = umsAddressMapper.selectAll();

        PageInfo<UmsAddress> pageInfo = new PageInfo<>(umsAddresses);
        return pageInfo;
    }

    @Override
    public Integer changeDefaultStatus(Long addressId) {
        UmsAddress umsAddress = umsAddressMapper.selectByPrimaryKey(addressId);
        int num;
        if(umsAddress.getDefaultStatus() == 0){
            umsAddress.setDefaultStatus(1);
            UmsAddress umsAddressSearch = umsAddressMapper.selectDefaultByUserId(umsAddress.getUserId());
            if(umsAddressSearch != null){
                umsAddressSearch.setDefaultStatus(0);
                umsAddressMapper.updateByPrimaryKey(umsAddressSearch);
            }
            num = umsAddressMapper.updateByPrimaryKey(umsAddress);
            return num;
        }
        return 0;
    }

    @Override
    public UmsAddress insert(UmsAddress umsAddress) {
        Long userId = umsAddress.getUserId();
        UmsAddress address = umsAddressMapper.selectDefaultByUserId(userId);
        //不管该用户有没有默认地址，当用户添加地址的时候把当前地址设为默认地址，后期可以通过后台管理系统进行默认地址的调整
        if(address != null){
            address.setDefaultStatus(0);
            umsAddressMapper.updateByPrimaryKey(address);
        }
        //插入该地址
        umsAddressMapper.insert(umsAddress);
        //再搜索一次UmsAddress(有address的id
        UmsAddress resAddress = umsAddressMapper.selectDefaultByUserId(userId);
        return resAddress;
    }

    @Override
    public Integer update(UmsAddress umsAddress) {
        return umsAddressMapper.updateByPrimaryKey(umsAddress);
    }

    @Override
    public String delete(Long addressId) {
        //默认地址不能删除
        UmsAddress umsAddress = umsAddressMapper.selectByPrimaryKey(addressId);
        if(umsAddress.getDefaultStatus() == 1){
            return "该地址为默认地址,不能删除";
        }
        if(umsAddressMapper.deleteByPrimaryKey(addressId) > 0){
            return "地址删除成功";
        }
        return "地址删除失败";
    }

    @Override
    public UmsAddress getOneById(Long id) {

        return umsAddressMapper.selectByPrimaryKey(id);
    }

    @Override
    public UmsAddress getDefaultAddressByUserId(Long userId) {
        return umsAddressMapper.selectDefaultByUserId(userId);
    }
}
